<template>
	<view class="page">
		<comHead :datas="datasObj"><template #soltcontent></template></comHead>

		<view class="content_box pd-30">

			<view class="upload_text_box bd-r40">
				<view class="ft-28 c-33 fw-800">发布内容</view>
				<view class="text_box bd-r40">
					<textarea class="textarea ft-24" v-model="form.content" placeholder="请输入内容"
						placeholder-class="textarea-placeholder" :maxlength="500" @input="" />
					<view class="text_box_bom ft-22 c-99">{{ form.content.length }} / 500</view>
				</view>
				<view class="img_model bd-r20 mt-20 pd-20">
					<text class="ft-24 c-99">添加图({{ form.images.length || 0 }}/9) | 视频({{ !form.video ? 0 : 1
					}}/1)</text>
					<view class="imgBox mt-30">
						<!-- 图片列表 -->
						<view class="img_list">
							<template v-if="form.images">
								<view class="imgItem" v-for="(item, index) in form.images" :key="index">
									<image class="imgs  bd-r20" :src="item" @click="openImg(index, form.images)"
										mode="aspectFill" />
									<image class="icon_samll icons"
										src="https://cdn.oss.bon-top.cn/static_bc/images/close_black.png"
										mode="aspectFit" @click="deleteImg(index, item)" />
								</view>
							</template>

							<view class="videoItem" v-if="form.video">
								<video :src="form.video" :controls="false" :playsinline="true" x5-playsinline
									webkit-playsinline class="preview-video"></video>
								<image class="icon_samll icons"
									src="https://cdn.oss.bon-top.cn/static_bc/images/close_black.png" mode="aspectFit"
									@click="deleteVideo()" />
							</view>

							<view class="imgUpload flex-center" v-if="!form.video && form.images.length < 9"
								@click="openUploadBtn()">
								<image class="icon_samll deg-90"
									src="https://cdn.oss.bon-top.cn/static_bc/images/add_icon1.png" mode="aspectFit">
								</image>
							</view>
						</view>
					</view>

				</view>
			</view>
			<!--  -->
			<view class="project_box bd-r40">
				<view class="flex-bwt"><text class="ft-28 c-33 fw-800">推荐项目<text class="ft-28 c-99">（非必填）</text></text>
					<image class="icon_samll icons" src="https://cdn.oss.bon-top.cn/static_bc/images/icon_left.png"
						mode="aspectFit" @click="addProject()" v-if="Object.keys(form.product_info)?.length" />
				</view>
				<view class="flex-bwt mt-20" v-if="!Object.keys(form.product_info)?.length" @click="addProject()">
					<text class="ft-24 c-99">请选择</text>
					<image class="icon_samll icons" src="https://cdn.oss.bon-top.cn/static_bc/images/icon_left.png"
						mode="aspectFit" @click="deleteImg(index, item)" />

				</view>
				<view class="list" v-if="Object.keys(form.product_info)?.length">
					<view class="item flex">
						<image class="icons fs0" :src="form.product_info.cover" mode="aspectFill" />
						<view class="name ft-28 c-33 fw-800 ml-10 te-2">{{ form.product_info.name }}</view>
					</view>
				</view>
			</view>
		</view>
		<view :style="{ height: (98 + 68) + 'rpx' }"></view>
		<view class="btn_box">
			<view class="box flex-bwt" style="height: 98rpx;">

				<view class="flex">
					<view class="btn mr-20" @click="submit(1)">存草稿</view>
					<view class="btn add" @click="submit(0)">发布</view>
				</view>
			</view>

		</view>
	</view>
	<!-- 选择视频/图片 -->
	<up-action-sheet :actions="list" :show="show" cancelText="取消" @close="close"
		@select="selectClick"></up-action-sheet>
</template>

<script setup lang="js">
import comHead from '@/components/comHead.vue';
import { onHide, onLoad, onShow } from '@dcloudio/uni-app';
import { ref, reactive, getCurrentInstance, onUnmounted } from 'vue';
import {
	utils
} from '@/utils/utils.js';
import {
	api
} from '@/utils/api.js';
const form = reactive({
	type: '',
	video: '',
	content: '',
	is_draft: '',
	images: [],
	items: [],
	product_id: [],
	product_info: []
})
let datasObj = reactive({
	title: '发布日常',
	img: '',
	color: '#FFFFFF',
	direction: '',
	scrollTop: 0,
	noBack: false,
	height: 88
})
const show = ref(false);
const list = ref([
	{
		name: '图片',
	},
	{
		name: '视频',
	},

]);
const uploadType = ref('')
let app = getApp()
const submit = (draft) => {
	let obj = { ...form }
	obj.is_draft = draft
	utils.request(
		api.submitSaleDaily, obj,
		"post"
	)
		.then((res) => {
			let title = ''
			if (draft) {

				title = '已存草稿'

			} else {
				title = '发布成功'

			}
			uni.showToast({
				title: title,
				icon: 'none',
				duration: 2000
			})
			uni.navigateTo({ url: '/subpackage/teacher/teacherDetail' })

		});
}
const addProject = () => {
	if (!app.globalData.isTeacherAdd) app.globalData.isTeacherAdd = true
	if (!app.globalData.projectIds?.length) app.globalData.projectIds = []
	if (!app.globalData.projectItem?.length) app.globalData.projectItem = []

	uni.navigateTo({
		url: '/subpackage/search/search',
	})
}
// 方法  
const selectClick = (item) => {
	console.log(item);
	uploadType.value = item.name
	upload()
};
const maxLength = ref(9)

const upload = async () => {
	if (uploadType.value == '视频') {
		const res = await uni.chooseVideo({
			sourceType: ['album', 'camera'],
			compressed: false // iOS需关闭压缩避免兼容性问题‌:ml-citation{ref="1,4" data="citationList"}
		})
		let obj = {
			url: res.tempFilePath,
			name: 'file',
			type: 'file'
		}
		const result = await uploadFilePromise('uploadVideo', obj);
		form.video = result
		console.log('form.video', form.video)

	} else {
		const res = await uni.chooseImage({
			sizeType: ['original'], // iOS需保留原图避免压缩异常‌:ml-citation{ref="3" data="citationList"}
			sourceType: ['album', 'camera']
		})
		console.log('res', res)
		let list = res.tempFilePaths.slice(0, Number(maxLength.value - form.images.length))
		for (let i = 0; i < list.length; i++) {
			let obj = {
				url: list[i],
				name: 'image',
				type: 'image'
			}
			const result = await uploadFilePromise('uploadImage', obj);
			form.images.push(result)
		}

	}
}
const openUploadBtn = () => {
	// 打开选项弹窗 没有选择数据的 情况
	if (!form.images.length && !form.video.length) {
		show.value = !show.value
	} else {
		upload()
	}
}
const close = () => {
	show.value = !show.value
}

// 删除图片
const deleteImg = (index, item) => {
	form.images = form.images.filter((f, i) => i !== index)
}
// 删除图片
const deleteVideo = () => {
	form.video = ''
}

const uploadFilePromise = (path, data) => {
	uni.showLoading({
		title: '请稍候...'
	})
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: utils.domain + '/api/v1/button.' + path,
			filePath: data.url,
			name: data.name,
			fileType: data.type,

			formData: {
				app_id: utils.app_id,
				identity: utils.identity,
			},
			header: {
				// 'content-type': 'multipart/form-data',
				'Authorization': utils.getToken()
			},
			success: (res) => {
				uni.hideLoading()
				const resData = JSON.parse(res.data)
				console.log('res', res)

				resolve(resData.data.info.url);
			},
		});
	});
};
const openImg = (index, imgList = []) => {
	uni.previewImage({
		current: index,
		urls: imgList
	});
}
const getSaleDailyDraft = () => {
	uni.showLoading()
	utils
		.request(
			api.getSaleDailyDraft, {},
			"get"
		)
		.then((res) => {
			console.log('res', res)
			uni.hideLoading()

			if (res.code == 200) {
				if (res.data.info) {
					let _data = res.data.info
					form.type = _data.type
					form.video = _data.video
					form.images = _data.images
					form.content = _data.content
					form.product_id = _data.product_id
					form.product_info = _data.product_info ? _data.product_info : {}
					app.globalData.projectItem = [form.product_info]
					app.globalData.projectIds = [form.product_id]
				}




			}
		});
}
onShow(() => {
	if (Object.keys(app.globalData).length) {
		form.product_info = app.globalData?.projectItem[0] ?? []
		form.product_id = app.globalData?.projectIds
	}
})
onLoad(() => {

	getSaleDailyDraft()

})
onUnmounted(() => {
	app.globalData.projectItem = null
	app.globalData.projectIds = null
	app.globalData.multiple = null
})
</script>

<style lang="scss">
.content_box {
	width: 100vw;
	border-top: 2rpx solid #F1F1F1;
	position: relative;

	.upload_text_box {
		background-color: #F8F8F8;
		padding: 20rpx;

		.text_box {
			background-color: #fff;
			height: 500rpx;
			padding: 0 20rpx;

		}

		.text_box_bom {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 20rpx;
			border-top: 2rpx solid #F1F1F1;

		}

		:deep(.textarea) {
			height: 420rpx;
			width: 100%;
			padding: 20rpx 0;
			font-size: 24rpx;
			color: #999;
			box-sizing: border-box;
			margin-top: 20rpx;

		}

		.img_model {
			background-color: #fff;

			.imgBox {
				display: flex;
				align-items: flex-end;

				.img_list {
					width: 100%;
					display: flex;
					flex-wrap: wrap;
					gap: 18rpx;

					.imgItem {
						// margin-right: auto;

						.imgs {
							width: 106rpx;
							height: 136rpx;
						}

						width: 106rpx;
						height: 136rpx;
						position: relative;

						.icons {
							position: absolute;
							right: 5rpx;
							top: 5rpx;
						}
					}

					.videoItem {
						width: 400rpx;
						height: 300rpx;
						box-sizing: border-box;
						margin: auto;
						position: relative;

						.preview-video {
							width: 400rpx;
							height: 250rpx;
						}

						.icons {
							width: 35rpx;
							height: 35rpx;
							position: absolute;
							right: 0;
							top: 0;
							z-index: 9999;
						}
					}

					:deep(.u-upload) {
						flex: 0 !important;
						margin-left: auto;
					}
				}

				.imgUpload {
					width: 106rpx;
					height: 136rpx;
					border-radius: 20rpx;
					border: 2rpx dashed #333;
					margin-left: auto;


				}


			}


		}
	}

	.project_box {
		margin: 20rpx 0;
		padding: 20rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, #FBFFDF, #F8F8F8);

		.list {
			box-sizing: border-box;

			.item {
				width: 100%;
				height: 158rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				margin-top: 20rpx;
				padding: 0 20rpx;
				box-sizing: border-box;


				.icons {
					width: 98rpx;
					height: 118rpx;
					border-radius: 20rpx;
				}
			}
		}
	}


}

.btn_box {
	width: 100%;
	position: fixed;
	left: 0;
	bottom: 0;
	box-sizing: border-box;
	background-color: #F8F8F8;
	padding-bottom: calc(10rpx + env(safe-area-inset-bottom));

	.btn_left {
		width: 132rpx;
		height: 54rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		line-height: 54rpx;
		text-align: center;
	}

	.btn {
		width: 192rpx;
		height: 78rpx;
		background: #F1F1F1;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		text-align: center;
		line-height: 78rpx;
		font-size: 28rpx;

	}

	.box {
		padding: 20rpx 30rpx 0;
		box-sizing: border-box;
		height: 98rpx;


		.add {
			width: 454rpx;
			color: #DBF046;
			background-color: #333333;
		}

	}
}

::v-deep .u-line {
	display: inline-block !important;
}
</style>
